﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Model
{
    [MessageHandler(AppType.Realm)]
    public class RegisterHandle : AMRpcHandler<C2R_Register, R2C_Register>
    {
        protected override async void Run(Session session, C2R_Register message, Action<R2C_Register> reply)
        {
            R2C_Register response = new R2C_Register();
            try
            {
                DBProxyComponent dBProxy = Game.Scene.GetComponent<DBProxyComponent>();
                List<AccountInfo> list = await dBProxy.QueryJson<AccountInfo>($"{"{\"AccountName\":\""}{message.Account}{"\"}"}");
                Log.Debug(list.Count.ToString());
                if (list.Count > 0)
                {
                    response.Error = ErrorCode.ERR_AccountOrPasswordError;
                    //response.Info = "fail";
                    reply(response);
                    return;
                }
                AccountInfo accountInfo = EntityFactory.CreateWithId<AccountInfo>(IdGenerater.GenerateId());
                accountInfo.AccountName = message.Account;
                accountInfo.Password = message.Password;

                await dBProxy.Save(accountInfo);
                //response.Info = "success";
                reply(response);
            }
            catch (Exception e)
            {
                Log.Debug("error");
                ReplyError(response, e, reply);
            }
        }
    }
}
